# Get US states shapefile us_shape = gpd.read_file(data_path + '/States_shapefile/States_shapefile.shp') us_shape = us_shape[['State_Name','geometry']] us_shape.head()
# plot the shape file with folium m = folium.Map(location=[50.77500, -100],zoom_start=3) choropleth =folium.GeoJson(data= us_shape.to_json()) m.add_child(choropleth)
# Get election data election = pd.read_csv(data_path + "/U.S. President 1976–2020/1976-2020-president.csv" ) election.replace('democratic-farmer-labor','democrat',inplace=True) election.head()
--- year state state_po state_fips state_cen state_ic office candidate party_detailed writein candidatevotes totalvotes version notes party_simplified 01976 ALABAMA AL 16341 US PRESIDENT CARTER, JIMMY DEMOCRAT False659170118285020210113 NaN DEMOCRAT 11976 ALABAMA AL 16341 US PRESIDENT FORD, GERALD REPUBLICAN False504070118285020210113 NaN REPUBLICAN 21976 ALABAMA AL 16341 US PRESIDENT MADDOX, LESTER AMERICAN INDEPENDENT PARTY False9198118285020210113 NaN OTHER 31976 ALABAMA AL 16341 US PRESIDENT BUBAR, BENJAMIN ""BEN"" PROHIBITION False6669118285020210113 NaN OTHER 41976 ALABAMA AL 16341 US PRESIDENT HALL, GUS COMMUNIST PARTY USE False1954118285020210113 NaN OTHER
defstate_style(state,year,function=False): """ Returns the style for a state in a given year """
state_results = results[year][state]
#Set state colour if state_results['dem'] >= state_results['rep']: color = '#4f7bff'#blue else: color = '#ff5b4f'#red
#Set state style if function == False: # Format for style_dictionary state_style = { 'opacity': 1, 'color': color, } else: # Format for style_fucntion state_style = { 'fillOpacity': 1, 'weight': 1, 'fillColor': color, 'color': '#000000'}
defyear_to_ts(year): """ Convert year to timestamp """ time = datetime.datetime(year, 1, 1, 0, 0).strftime('%s') iflen(time)==9: time ='0{}'.format(time) return time
上面提到的 ID 是分配给每个州的唯一
ID。它由.to_json()函数自动分配。TimeSliderChoropleth
使用这些 ID
将州映射到其样式。因此,为了确保我们有正确的映射,我们首先创建从 ID
到州名的映射。这在下面的第 7 行到第 13
行中完成。该函数的其余部分使用上面看到的形式创建字典。
defgetFigure(state): """ Plot voting trends from a given state """
#Get number of votes years = range(1976,2024,4) dems = [] reps =[] for year in years:
result = results[year][state] dems.append(result['dem']/1000000) reps.append(result['rep']/1000000)
#Plot number of votes fig = plt.figure(figsize=(8,4)) plt.plot(years,dems,label='Democrat',color='#4f7bff') plt.plot(years,reps,label='Republican',color='#ff5b4f')